package concurrent.application;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.*;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2021-06-01 14:40:00
 */
@Slf4j
public class CyclicBarrierDemo {

    @Test
    public void test01() throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.info("等待子任务全部执行完毕～");
        });
        ExecutorService service = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 2; i++) {
            service.submit(() -> {
                try {
                    log.info("子任务开始");
                    cyclicBarrier.await();
                    log.info("子任务结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        Thread.currentThread().join();
    }

    /**
     * 可复用，各个线程串行执行step1、step2、step3
     * @throws InterruptedException
     */
    @Test
    public void test02() throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.info("---");
        });
        ExecutorService service = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 2; i++) {
            service.submit(() -> {
                try {
                    log.info("step1");
                    cyclicBarrier.await();
                    log.info("step2");
                    cyclicBarrier.await();
                    log.info("step3");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        Thread.currentThread().join();
    }

}
